package com.mall.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.mall.common.model.GlobalResponse;
import com.mall.dao.UserMapper;
import com.mall.enums.GlobalResponseEnum;
import com.mall.enums.RoleEnum;
import com.mall.pojo.User;
import com.mall.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;


@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;
    /**
     * @param user
     */
    @Override
    public GlobalResponse register(User user) {

        /*username不重复*/
        if (userMapper.countByUsername(user.getUsername())>0){
            return GlobalResponse.error(GlobalResponseEnum.USERNAME_EXIST);

        }

        /*email不重复*/
        if (userMapper.countByEmail(user.getEmail())>0){
            return GlobalResponse.error(GlobalResponseEnum.EMAIL_EXIST);
        }

        user.setRole(RoleEnum.CUSTOMER.getCode());
        /*MD5摘要算法*/
        user.setPassword(SecureUtil.md5(user.getPassword()));
        int result = userMapper.insertSelective(user);
        if (result==0) {
            return GlobalResponse.error(GlobalResponseEnum.ERROR);
        }
        return GlobalResponse.success();
    }

    /**
     * @param username
     * @param password
     * @return
     */
    @Override
    public GlobalResponse<User> login(String username, String password) {
        User user = userMapper.selectByUsername(username);
        if (user==null){
            /*用户名不存在*/
            return GlobalResponse.error(GlobalResponseEnum.USER_OR_PASSWORD_ERROR);
        }
        if (!Objects.equals(user.getPassword(),SecureUtil.md5(password))) {
            /*密码错误*/
            return GlobalResponse.error(GlobalResponseEnum.USER_OR_PASSWORD_ERROR);
        }
        user.setPassword("");
        return GlobalResponse.successByData(user);
    }


}
